<template>
	<view ref="home" id="home" class="home" :style="{'backgroundImage':homeType==1?`url(${homeBg})`:''}">
		<header-new></header-new>
		<header-left></header-left>
		<WorkOrder></WorkOrder>
		<view v-if='homeType==1&&item.width' v-for="(item,index) in house" :key="index+'house'" class="house"
			:class="{'houseAlarm':item.status==1,'houseFault':item.status==0||item.status==4}"
			:style="{left:item.screenx,top:item.screeny,width:item.width,height:item.height}"
			@mouseover="item.show=true" @mouseleave="item.show=false" @click="jump(item.buildId,item.id)">
			<view class="alarmSituation alarmSituationOne">
				<!-- 故障 -->
				<view class="titleInfo" v-if="item.status==0||item.status==4">
					<view class="titleInfoTop">
						<image src="../../static/fault-icon.png" class="img" />
						<view class="titleD" @mouseover="showMouseEnter($event,item)" @mouseout="showMouseOut">
							{{item.name}} {{item.faultFloorText}}</view>
					</view>
					<view class="titleBox">
						<view class="titleInfoB" @mouseover="showMouseBottomEnter($event,item)"
							@mouseout="showMouseOut">
							累计{{item.faultSystemText}}发生故障。
						</view>
					</view>
				</view>
				<!-- 报警 -->
				<view class="titleInfo" v-else-if="item.status==1">
					<view class="titleInfoTop">
						<image src="../../static/alarm-icon.png" class="img" />
						<view class="titleD" @mouseover="showMouseEnter($event,item)" @mouseout="showMouseOut">
							{{item.name}} {{item.alarmFloorText}}</view>
					</view>
					<view class="titleBox">
						<view class="titleInfoB" @mouseover="showMouseBottomEnter($event,item)"
							@mouseout="showMouseOut">
							累计{{item.alarmSystemText}}发生报警！
						</view>
					</view>
				</view>
				<!-- 正常 -->
				<view v-else class="normalTitle" @mouseover="showMouseEnter($event,item)" @mouseout="showMouseOut">
					<div class='normalTitleIn'>{{item.name}}</div>
				</view>
				<view class="lineInfo"></view>
			</view>
			<view class="alarmSituation alarmSituationTwo"></view>
		</view>
		<view v-if="homeType!== 1" class="chartMain" style="width: 100%;height: 100%;">
			<el-amap vid="amap" :zoom="zoom" :plugin="plugin" :events="mapevents" :amap-manager="amapManager"
				:resizeEnable='true' :rotateEnable="true" pitch=60 :expandZoomRange="true" :zooms="zooms"
				:buildingAnimation="true" class="amap-mark" :center="center" :viewMode='vmode' @touchstart="touchStart"
				@touchmove="touchMove">
			</el-amap>
			<view class="buildPop">
				<view class="topImg" @click="showBuild" :class="{'top-img-active':buildListShow}">
					<image src="../../static/img/buildIcon.png" class="img" />
				</view>
				<view class="textName" @click="showBuild" :class="{'top-name-active':buildListShow}">全部建筑</view>
				<view class="allBuildList" v-if="buildListShow">
					<view class="topText">全部建筑</view>
					<scroll-view scroll-y="true" @scrolltolower="lower" class="everyMain">
						<span class="everyBorder" v-for="(item,index) in everyBuildList" :key="index"
							@click.stop="everyBorderClick(item,index)">
							<span class="everyBuildList"
								:class="{'every-active':everyBuildIndex===index}">{{item.buildingName}}</span>
						</span>
					</scroll-view>
					<!-- 关闭按钮 -->
					<image src="../../static/img/close.png" mode="" class="close-png pointer" @tap.stop="closeBuild">
					</image>
				</view>
			</view>
		</view>
		<Tooltip></Tooltip>
	</view>
</template>

<script>
	import headerLeft from "../../component/home/HomeLeft.vue"
	import WorkOrder from "../../component/home/WorkOrder.vue"
	import {
		AMapManager
	} from "vue-amap";
	let amapManager = new AMapManager();
	let cluster = null;
	export default {
		components: {
			headerLeft,
			WorkOrder
		},
		data() {
			let self = this;
			return {
				title: 'Hello',
				house: [],
				homeBg: '',
				hoverImgIndex: 0,
				hoverHouse: [],
				leftFlag: false,
				//首页显示类别:1为平面图,2为高德地图
				homeType: JSON.parse(uni.getStorageSync('user')).aioHomePageType || 2,
				amapManager,
				zoom: 5,
				zooms: [3, 20],
				center: [114.425817, 30.423406],
				vmode: "3D",
				plugin: [{
					pName: "AMap.Geolocation",
					events: {
						init(o) {
							// o 是高德地图定位插件实例
							setTimeout(() => {
								let map = amapManager.getMap();
								if(self.homeType == 3){
									map.setZoom(19.5)
									self.zoom = 19.5
								}else{
									map.setZoom(18.6)
									self.zoom = 18.6
								}
							}, 1600)
						}
					}
				}],
				mapevents: {
					init: o => {
						o.setMapStyle("amap://styles/" +
							(uni.getStorageSync('mapId') ? uni.getStorageSync('mapId') : "normal")
						);
					}
				},
				markerRefs: [],
				markers: [],
				mapLoad: false,
				houseMap: [], //高德地图下的建筑列表

				showFlag: true,

				startDistance: 0, //双指触摸时初始距离
				endDistance: 0, //双指移动时距离
				startObj: null, //单指触摸时初始位置

				buildListShow: false,
				everyBuildIndex: -1,
				buildPage: {
					pageNum: 1,
					pageSize: 20
				},
				moreFlag: false,
				buildLoading: false,
				everyBuildList: [], //建筑弹框列表
				scaleWidth:1, //宽缩放
				scaleHeight:1, //高度缩放
			}
		},
		created() {
			let self = this
			let userObj = JSON.parse(uni.getStorageSync('user'))
			if (uni.getStorageSync('webSocketUserId') != userObj.userId) {
				//登录用户和之前不同时直接打开webSocket
				this.initWebSocket()
			} else {
				//登录用户未变时
				uni.sendSocketMessage({ //监听是否有websocket启动
					data: 'HeartBeat',
					success() { //已启动则不重复启动
						console.log('webSocket已连接')
					},
					fail() { //未启动则启动连接
						console.log('发送心跳失败')
						self.initWebSocket()
					}
				})
			}
			
			//获取屏幕信息
			let systemInfo=uni.getWindowInfo()
			this.scaleWidth=systemInfo.windowWidth/1920
			this.scaleHeight=systemInfo.windowHeight/1200
			console.log(systemInfo)

			window.showSensor = this.showSensor
			window.showMouseEnter = this.showMouseEnter
			window.showMouseBottomEnter = this.showMouseBottomEnter
			window.showMouseOut = this.showMouseOut
			let latLud = userObj.latLud
			if (latLud) { //如果登录账户的单位经纬度存在则修改定位中心点
				this.center=latLud.split(',')
			}
			this.getList()
			if(this.homeType == 3){
				setTimeout(function() {
					self.getMap3d()
				}, 1000)
			}
			this.getEveryBuildList()

			//刷新
			uni.$on('globalRefresh', function() {
				self.getList()
			})
			//更新地图位置到点击的实时数据的对应建筑位置
			if (this.homeType !== 1) {
				uni.$on('selectedAddress', function(data) {
					self.selectedAddress(data)
				})
			}
		},
		methods: {
			//加载3D模型
			getMap3d() {
				let self = this
				// 创建Object3DLayer图层
				var object3Dlayer = null;
				AMap.plugin(["AMap.Object3DLayer"], function() {
					object3Dlayer = new AMap.Object3DLayer();
					let map = amapManager.getMap()
					map.add(object3Dlayer);

					var druckMeshes, cityMeshes;
					AMap.plugin(["AMap.GltfLoader"], function() {
						let latLud = JSON.parse(uni.getStorageSync('user')).latLud
						let position = [114.425817, 30.423406]
						
						if (latLud) { //如果登录账户的单位经纬度存在则修改定位中心点
							position = latLud.split(',')
						}
						var urlCityList = [
							{
								url: 'static/model/t1/t1.gltf'
							}
						]
						var gltfObj = new AMap.GltfLoader();
						let paramCity = {
							position: new AMap.LngLat(position[0], position[1]), // 必须
							scale: 30, // 非必须，默认1
							height: 10, // 非必须，默认0
							scene: 0, // 非必须，默认0
						};
						urlCityList.forEach(function(item) {
							gltfObj.load(item.url, function(gltfCity) {
								cityMeshes = gltfCity;
								gltfCity.setOption(paramCity);
								gltfCity.rotateX(88);
								gltfCity.rotateZ(218);
								object3Dlayer.add(gltfCity);
							});
						})
					});
				})
			},
			//建筑列表滚动加载
			lower() {
				if (!this.moreFlag && !this.buildLoading) {
					this.buildPage.pageNum += 1
					this.getEveryBuildList()
				}
			},
			async getEveryBuildList() {
				this.buildLoading = true
				let res = await this.$api.buildingPage({
					pageNum: this.buildPage.pageNum,
					pageSize: this.buildPage.pageSize
				})
				this.everyBuildList = this.everyBuildList.concat(res.data.list)
				if (this.everyBuildList.length >= res.data.total) {
					this.moreFlag = true
				}
				this.buildLoading = false
			},
			//选择建筑弹框，切换地图显示
			everyBorderClick(item, index) {
				this.everyBuildIndex = index
				if (item.latLud) {
					this.selectedAddress(item)
				}
			},
			//显示建筑列表
			showBuild() {
				this.buildListShow = true
			},
			closeBuild() {
				this.buildListShow = false
				this.everyBuildIndex = -1
			},
			selectedAddress(item) {
				let lnglat = item.latLud.split(",");
				let self = this;
				if (lnglat) {
					//将gps坐标转为高德坐标
					AMap.convertFrom(lnglat, 'gps', function (status, result) {
					  if (result.info === 'ok') {
					    var resLnglat = result.locations[0];
						self.center = [resLnglat.lng,resLnglat.lat];
						let map = amapManager.getMap();
						map.setZoom(18)
						self.zoom = 18
					  }
					});
				}
			},
			translateMap(x, y) {
				let map = amapManager.getMap();
				map.panBy(x, y);
			},
			touchStart(e) {
				console.log(e)
				if (e.touches.length >= 2) { //判断是双指以上触摸
					// 初始两指距离
					this.startDistance = this.getDistance(e.touches)
				} else {
					this.startObj = e.touches[0]
				}
			},
			touchMove(e) {
				if (e.touches.length >= 2) { //判断是双指以上触摸
					// 移动时两指距离
					this.endDistance = this.getDistance(e.touches)
					//缩放比例
					let map = amapManager.getMap();
					let scale = this.zoom * this.startDistance / this.endDistance
					map.setZoom(scale)
					console.log(scale + '--缩放-' + this.zoom)
					this.zoom = scale
				} else if (e.touches.length == 1) {
					let x = e.touches[0].pageX - this.startObj.pageX
					let y = e.touches[0].pageY - this.startObj.pageY
					this.translateMap(x, y)
					console.log(x + '--平移-' + y)
				}
			},
			getDistance(start, stop) {
				return Math.sqrt(Math.pow((stop[1].pageX - start[0].pageX), 2) + Math.pow((stop[1].pageY - start[0].pageY),
					2));
			},
			async getList() {
				let that = this
				let urlP = uni.getStorageSync('urlText') + '/admin/sys-file/'
				let netWorkFlag= await this.$help.getNetWork()
				if (netWorkFlag) { //网络正常
					if (this.homeType == 1) { //显示平面图时
						that.house = []
						let res = await this.$api.getBuildingPage({
							screenShow: '1'
						})
						res.data.forEach((item) => {
							if (item.status == 0) { //故障 数据显示处理
								item.faultFloorText = that.dataChange(item.faultFloorList, 'floor')
								item.faultSystemText = that.dataChange(item.faultSystemList, 'system')
							} else if (item.status == 4) { //报警
								item.faultFloorText = that.dataChange(item.offlineFloorList, 'floor')
								item.faultSystemText = that.dataChange(item.offlineSystemList, 'system')
							} else if (item.status == 1) { //报警
								item.alarmFloorText = that.dataChange(item.alarmFloorList, 'floor')
								item.alarmSystemText = that.dataChange(item.alarmSystemList, 'system')
							}
							this.house.push({
								id: item.deptId,
								name: item.buildName,
								buildId: item.buildId,
								screenx: (item.screenx*that.scaleWidth) + 'px',
								screeny: (item.screeny*that.scaleHeight) + 'px',
								imgUrl: urlP + item.hoverRendering,
								hoverRendering: item.hoverRendering,
								alarmFloorText: item.alarmFloorText || '',
								alarmSystemText: item.alarmSystemText || '',
								faultFloorText: item.faultFloorText || '',
								faultSystemText: item.faultSystemText || '',
								show: false,
								status: item.status
							})
						})
						this.house.map(function(itm, ind) {
							uni.getImageInfo({
								src: itm.imgUrl,
								success: function(image) {
									itm.width = (image.width*that.scaleWidth) + 'px'
									itm.height = (image.height*that.scaleHeight) + 'px'
									console.log('image' + ind)
									that.house.splice(ind, 1, itm)
								},
								fail() {
									console.log('ddd')
								}
							})
							that.getImageUrl(itm.hoverRendering, 'signalChat', 'img', 'hoverRendering' + ind,
								'hoverRendering' + ind, itm, ind)
						})
					} else { //显示高德地图时
						that.houseMap = []
						let res = await this.$api.getBuildingPage()
						let mapIndex = 0
						res.data.forEach((item) => {
							let latlud = item.latLud ? item.latLud.split(',')[0] : ''
							if (!latlud || latlud == 'null' || latlud == 'NaN') {
								item.latLud = "114.425817,30.423406"
							}
							if (item.status == 0) { //故障 数据显示处理
								item.faultFloorText = that.dataChange(item.faultFloorList, 'floor')
								item.faultSystemText = that.dataChange(item.faultSystemList, 'system')

							} else if (item.status == 4) { //报警
								item.faultFloorText = that.dataChange(item.offlineFloorList, 'floor')
								item.faultSystemText = that.dataChange(item.offlineSystemList, 'system')
							} else if (item.status == 1) { //报警
								item.alarmFloorText = that.dataChange(item.alarmFloorList, 'floor')
								item.alarmSystemText = that.dataChange(item.alarmSystemList, 'system')
							}
							//将gps坐标转为高德坐标
							let x=Number(item.latLud.split(",")[0])
							let y=Number(item.latLud.split(",")[1])
							
							AMap.convertFrom([x,y], 'gps', function (status, result) {
								console.log(status)
								console.log(result)
							  if (result.info === 'ok') {
							    var resLnglat = result.locations[0];
							    
								item.latLud = resLnglat.lng + ',' + resLnglat.lat
								
								that.houseMap.push({
									resLnglat:resLnglat,
									id: item.deptId,
									name: item.buildName,
									buildId: item.buildId,
									alarmFloorText: item.alarmFloorText || '',
									alarmSystemText: item.alarmSystemText || '',
									faultFloorText: item.faultFloorText || '',
									faultSystemText: item.faultSystemText || '',
									latLud: item.latLud,
									status: item.status,
								})
							  }
							  mapIndex ++
							});
						})
						//判断所有gps经纬度转换高德经纬度完成后，再加载标记点
						let timerMap = setInterval(()=>{
							if(mapIndex >= res.data.length){
								console.log(that.houseMap)
								clearInterval(timerMap)
								timerMap = null
								that.getmapMarks(that.houseMap)
								that.$help.updateData(that.$db, that.houseMap, 'name', 'getBuildingPage')
							}
						},1000)
						
					}
				} else { //无网络时
					if (this.homeType == 1) { //显示平面图时
						that.$help.getLocalData(that.$db, 'name', 'buildingPage').then(function(data) {
							if (data) {
								that.house = data
							} else {
								that.house = []
							}
						})
					} else { //显示高德地图时
						that.$help.getLocalData(that.$db, 'name', 'getBuildingPage').then(function(data) {
							if (data) {
								that.houseMap = data
							} else {
								that.houseMap = []
							}
							that.getmapMarks(that.houseMap)
						})
					}

				}
				if (this.homeType == 1) { //显示平面图时
					if (uni.getStorageSync('largeScreenBackground')) { //背景图有本地存储时
						that.$help.getLocalData(that.$db, 'name', 'largeScreenBackground').then(function(data) {
							if (data) {
								that.homeBg = data
							} else {
								that.homeBg = urlP + JSON.parse(uni.getStorageSync('user'))
									.largeScreenBackground
							}
						})
					} else {
						that.homeBg = urlP + JSON.parse(uni.getStorageSync('user')).largeScreenBackground
					}
				}
			},
			//数据转换
			dataChange(data, type) {
				let text = ''
				if (data && data.length) { //数据列表存在
					text = ''
					data.forEach((itm) => {
						if (type === 'floor') {
							text += itm + 'F/'
						} else {
							text += itm.number + '个' + itm.systemName + ','
						}

					})
					text = text.slice(0, -1)
				}
				return text
			},

			leftClick() {
				this.leftFlag = !this.leftFlag
			},
			jump(buildId, deptId) {
				// 点击跳转
				this.house.forEach(v => {
					v.show = false
				})
				this.buildListShow=false
				//使用redirectTo,触发组件销毁事件,清楚定时器之类
				uni.navigateTo({
					url: '../newDetail/newDetail?buildId=' + buildId + '&deptId' + '=' + deptId
				})
			},
			// url 图片地址
			// storeName indexedDB的仓库名称
			// sequenceId  索引sequenceId的值
			// messageType 索引messageType的值及设置对应保存图片是否本地保存的对应字段
			// nameValue   sqlite的name的值
			getImageUrl(url, storeName, sequenceId, messageType, nameValue, itm, ind) {
				let that = this
				uni.request({
					url: uni.getStorageSync('urlText') + '/admin/sys-file/' + url,
					method: 'GET',
					responseType: 'arraybuffer',
					success: ress => {
						let base64 = 'data:image/jpeg;base64,' + uni.arrayBufferToBase64(ress
							.data); //把arraybuffer转成base64
						that.hoverImgIndex += 1
						console.log(that.hoverImgIndex)
						itm.imgUrl = base64
						that.hoverHouse[ind] = itm
						if (that.hoverImgIndex >= that.house.length) {
							console.log(that.hoverHouse.length)
							that.$help.updateData(that.$db, that.hoverHouse, 'name', 'buildingPage')
							that.hoverImgIndex = 0
						}
					},
					fail: () => {
						console.log("图片转换失败");
					}
				})
			},
			showSensor(item) { //地图标点 点击跳转
				this.jump(item.buildId, item.id)
			},
			showMouseBottomEnter(e, item) { //鼠标移入弹框显示
				let data = ""
				if (item.status == 0 || item.status == 4) { //故障
					data = '累计' + item.faultSystemText + '发生故障。'
				} else if (item.status == 1) { //报警
					data = '累计' + item.alarmSystemText + '发生报警！'
				}
				this.$bus.$emit('show-tooltip', [{
						type: 0,
						text: data
					},
					e.pageX,
					e.pageY
				])
			},
			showMouseEnter(e, item) { //鼠标移入弹框显示
				let data = ""
				if (item.status == 0 || item.status == 4) { //故障
					data = item.name + ' ' + item.faultFloorText
				} else if (item.status == 1) { //报警
					data = item.name + ' ' + item.alarmFloorText
				} else if (item.status == 2) { //正常
					data = item.name
				}
				this.$bus.$emit('show-tooltip', [{
						type: 0,
						text: data
					},
					e.pageX,
					e.pageY
				])
			},
			showMouseOut() { //鼠标移出弹框隐藏
				this.$bus.$emit('hide-tooltip')
			},
			getmapMarks(ormarks) {
				//获取地图建筑标记点
				if (cluster) {
					console.log('cluster')
					cluster.clearMarkers()
				}
				let map = amapManager.getMap();
				if (map) {
					console.log('map')
					map.clearMap();
				}
				this.mapLoad = true
				let self = this;
				if (ormarks.length > 0) {
					self.markerRefs = []
					self.markers = []
					ormarks.map((item, index) => {
						let html = ""
						if (item.status == 0 || item.status == 4) { //故障
							html += "<div class='houseBox houseFault'>"
						} else if (item.status == 1) { //报警
							html += "<div class='houseBox houseAlarm'>"
						} else if (item.status == 2) { //正常
							html += "<div class='houseBox'>"
						}
						if (item.status == 2) { //正常
							html += `<div class='alarmSituation alarmSituationOne'>
										</div>
										<div class='alarmSituation alarmSituationTwo'></div>
										<div class="normalTitle"  onclick='showSensor(${JSON.stringify(item)})' ontouchstart='showSensor(${JSON.stringify(item)})' onmouseover='showMouseEnter(event,${JSON.stringify(item)})' onmouseout='showMouseOut()'><div class='normalTitleIn'>${item.name}</div></div>
										<div class='lineInfo'></div>
									</div>`
						} else if (item.status == 1) { //报警
							html += `<div class='alarmSituation alarmSituationOne' >
							</div>
							<div class='alarmSituation alarmSituationTwo'></div>
							<div class='titleInfo' onclick='showSensor(${JSON.stringify(item)})' ontouchstart='showSensor(${JSON.stringify(item)})'>
								<div class='titleInfoTop'>
									<div class='img'></div>
									<div class='titleD' onmouseover='showMouseEnter(event,${JSON.stringify(item)})' onmouseout='showMouseOut()'>${item.name} ${item.alarmFloorText}</div>
								</div>
								<div class='titleBox'>
									<div class='titleInfoB' onmouseover='showMouseBottomEnter(event,${JSON.stringify(item)})' onmouseout='showMouseOut()'>
										累计有${item.alarmSystemText}发生报警！
									</div>
								</div>
							</div>
							<div class='lineInfo'></div>
							</div>`
						} else if (item.status == 0 || item.status == 4) { //故障
							html += `<div class='alarmSituation alarmSituationOne'>
							</div>
							<div class='alarmSituation alarmSituationTwo'></div>
							<div class='titleInfo'  onclick='showSensor(${JSON.stringify(item)})' ontouchstart='showSensor(${JSON.stringify(item)})'>
								<div class='titleInfoTop'>
									<div class='img'></div>
									<div class='titleD' onmouseover='showMouseEnter(event,${JSON.stringify(item)})' onmouseout='showMouseOut()'>${item.name} ${item.faultFloorText}</div>
								</div>
								<div class='titleBox'>
									<div class='titleInfoB' onmouseover='showMouseBottomEnter(event,${JSON.stringify(item)})' onmouseout='showMouseOut()'>
										累计有${item.faultSystemText}发生故障。
									</div>
								</div>
							</div>
							<div class='lineInfo'></div>
							</div>`
						}						
						let obj = {
							position: [Number(item.latLud.split(",")[0]), Number(item.latLud.split(",")[1])],
							id: item.id,
							status: item.status,
							name: item.name,
							content: html,
						}
						self.markers.splice(index, 1, obj)
						self.mapObj = new AMap.Marker(obj)
						self.markerRefs.push(self.mapObj)
					});
					//点聚合
					this.getMapcluster()
				} else {
					this.mapLoad = false
				}

			},
			getMapcluster() {
				let self = this;
				setTimeout(function() {
					let map = amapManager.getMap();
					map.plugin('AMap.MarkerClusterer', function() {
						cluster = new AMap.MarkerClusterer(map, self.markerRefs, {
							gridSize: 280,
							minClusterSize: 2,
							maxZoom: 17,
							renderCluserMarker: self._renderCluserMarker
						});
					});
					self.mapLoad = false;
				}, 1000)
			},
			_renderCluserMarker(context) {
				// 点聚合方法
				const count = this.markerRefs.length;

				let factor = Math.pow(context.count / count, 1 / 18);
				let div = document.createElement('div');
				let Hue = 180 - factor * 180;
				let bgColor = 'hsla(167,72%,60%,0.3)';
				let fontColor = 'hsla(0,0%,100%,1)';
				let borderColor = 'hsla(167,72%,60%,1)';
				let shadowColor = 'hsla(' + Hue + ',100%,50%,1)';
				div.style.backgroundColor = bgColor
				let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
				div.style.width = div.style.height = size + 'px';
				div.style.border = 'solid 1px ' + borderColor;
				div.style.borderRadius = size / 2 + 'px';
				div.style.boxShadow = '0 0 1px ' + shadowColor;
				div.innerHTML = context.count;
				div.style.lineHeight = size + 'px';
				div.style.color = fontColor;
				div.style.fontSize = '14px';
				div.style.textAlign = 'center';
				context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
				context.marker.setContent(div)
			},

			//websocket连接
			getuuid() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			webSendMessage() {
				this.sendTimeout = setInterval(function() {
					// 定时发送心跳包
					uni.sendSocketMessage({
						data: 'HeartBeat'
					})
				}, 30000)
			},
			webSocketMessage(res) {
				let redata = JSON.parse(res.data);
				if (redata.type === 1) { //视频报警
					uni.$emit('videoshow', {
						status: redata.status
					})
				} else { //判断是设备报警
					if (redata.status === 1) { //设备报警状态
						uni.$emit('alarmshow', {
							status: redata.status
						})
					} else if (redata.status === 0) { //设备故障状态
						uni.$emit('abnormalshow', {
							status: redata.status
						})
					} else if (redata.status === 2) { //设备正常状态
						uni.$emit('alarmshow', {
							status: redata.status
						})
						uni.$emit('abnormalshow', {
							status: redata.status
						})
					}
				}
			},
			closeSocketStatus() {
				let self = this
				uni.onSocketClose(function() {
					console.log('WebSocket 已关闭！');
					if (self.sendTimeout) {
						clearInterval(self.sendTimeout)
						self.sendTimeout = null
					}
					let timer = setTimeout(function() {
						console.log('重连')
						self.initWebSocket()
						clearTimeout(timer)
						timer = null
					}, 3000)
				});
			},
			closeWebSocket() {
				let self = this
				uni.closeSocket({
					url: self.websocketUrl
				})
			},
			initWebSocket() {
				let token = this.getuuid();
				let self = this
				let useObj = JSON.parse(uni.getStorageSync('user'))
				let wsUrl = ''
				if (uni.getStorageSync('urlText').split('//')[0] === 'https:') {
					wsUrl = 'wss://'
				} else {
					wsUrl = 'ws://'
				}
				// 线上发布-小程序必须用wss协议
				self.websocketUrl = wsUrl + uni.getStorageSync('urlText').split('//')[1] + "/admin/message/" + useObj.userId + '/' + token
				uni.connectSocket({
					url: self.websocketUrl
				});
				uni.onSocketOpen(function() {
					console.log('WebSocket连接已打开！');
					self.webSendMessage()
					//保存当前连接成功的webSocket的用户id
					uni.setStorageSync('webSocketUserId', useObj.userId)
				});
				uni.onSocketMessage(function(res) {
					self.webSocketMessage(res)
				});
				this.closeSocketStatus()
			},
		},
		beforeDestroy() {
			uni.$off('globalRefresh')
		}
	}
</script>

<style lang="scss" scoped>
	.home {
		overflow: hidden;
		width: 100%;
		height: 100%;
		margin: 0 auto;
		background: no-repeat;
		background-size: 100% 100%;
		position: relative;
		color: #eee;
		.h-left {
			width: 400px;
			position: absolute;
			top: 110px;
			left: 15px;
			padding-right: 50px;
			z-index: 1;

			.left1 {
				margin-bottom: 10px;
			}

			.left2 {
				margin-bottom: 10px;
			}

			.homeChange {
				cursor: pointer;
				position: absolute;
				right: 0;
				top: 50%;

				image {
					width: 45px;
					height: 45px;
				}
			}

			transform: translateX(0);
			transition: 0.5s;
		}

		.h-left-active {
			transform: translateX(-365px);
		}

		.h-right {
			position: absolute;
			top: 110px;
			right: 15px;
			padding-left: 50px;

			.right1 {
				margin-bottom: 10px;
			}

			.homeChangeR {
				cursor: pointer;
				position: absolute;
				left: 0;
				top: 50%;

				image {
					width: 45px;
					height: 45px;
				}
			}

			transform: translateX(0);
			transition: 0.5s;
		}

		.h-right-active {
			transform: translateX(575px);
		}

		.h-right-active2 {
			transform: translateX(5.12rem);

		}

		.h-right {
			position: absolute;
			top: 110px;
			right: 15px;
			padding-left: 50px;
			z-index: 1;

			.right1 {
				margin-bottom: 10px;
			}

			.homeChangeR {
				cursor: pointer;
				position: absolute;
				left: 0;
				top: 50%;

				image {
					width: 45px;
					height: 45px;
				}
			}

			transform: translateX(0);
			transition: 0.5s;
		}

		.h-right-active {
			transform: translateX(575px);
		}

		.house {
			position: absolute;
			cursor: pointer;
			width: 370px;
			height: 332px;
			background-size: 100% 100% !important;
		}

		.normalTitle {
			left: -41px;
		}

		@keyframes circleBuild {
			0% {
				transform: rotateZ(0deg);
			}

			100% {
				transform: rotateZ(360deg);
			}
		}

		@keyframes circleBuildReverse {
			0% {
				transform: rotateZ(0deg);
			}

			100% {
				transform: rotateZ(-360deg);
			}
		}

		.chartMain {
			.buildPop {
				position: fixed;
				bottom: 30px;
				left: 50%;
				transform: translateX(-50%);
				display: flex;
				flex-direction: column;
				align-items: center;

				.topImg {
					width: 50px;
					height: 50px;
					background: url("../../static/img/buildCircle.png") center no-repeat;
					background-size: 100% 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					cursor: pointer;

					uni-image {
						width: 24px;
						height: 24px;
					}

					&.top-img-active {
						animation: circleBuild linear 5s infinite;

						uni-image {
							animation: circleBuildReverse linear 5s infinite;
						}
					}
				}

				.textName {
					color: rgba(255, 255, 255, .6);
					font-size: 16px;
					padding-top: 7px;
					cursor: pointer;

					&.top-name-active {
						color: #02C3FF;
					}
				}


				.allBuildList {
					position: absolute;
					width: 746px;
					padding: 20px 10px 20px 30px;
					background: rgba(3, 48, 94, 0.7);
					backdrop-filter: blur(2px);
					top: -200px;
					left: 50%;
					transform: translateX(-50%);

					.topText {
						font-size: 18px;
						color: #fff;
						line-height: 26px;
						margin-bottom: 20px;
					}

					.everyMain {
						height: 92px;
						.everyBorder {
							display: inline-block;
							border: 1px solid;
							border-image: linear-gradient(180deg, rgba(2, 195, 255, 0.5), rgba(2, 195, 255, 0.25)) 1 1;
							border-radius: 2px;
							margin-bottom: 10px;
							margin-right: 10px;
							cursor: pointer;
						}

						.everyBuildList {
							display: inline-block;
							padding: 6px 20px;
							line-height: 22px;
							font-size: 16px;
							color: rgba(255, 255, 255, 0.7);

							&.every-active {
								background: linear-gradient(180deg, rgba(0, 173, 255, 0.94) 0%, rgba(17, 51, 82, 0) 60%);
								color: #fff;
							}
						}
					}

					.close-png {
						position: absolute;
						right: 20px;
						top: 20px;
						width: 14px;
						height: 14px;
					}
				}
			}
		}
	}
</style>
